/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.Float.parseFloat;
import static java.lang.Integer.parseInt;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.*;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Belal Salah
 */
public class RegisterationServlet extends HttpServlet {

    private static final String UPLOAD_DIRECTORY = "uploads";
    private String firstname, lastname, mobile, mail, address, password;
    private int day, month, year;
    private float credit;
    private boolean isMultipart;
    private String filePath;
    private int maxFileSize = 50 * 1024;
    private int maxMemSize = 4 * 1024;
    private File file;
    private String result="";
    @Override
     public void init() {
// Get the file location where it would be stored.
        filePath = getServletContext().getRealPath("/");
        String search="build";
        int index=filePath.indexOf(search);
        if(index !=-1){
            result=filePath.substring(0, index);
            
        }
        result=result+"web/uploads/";

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        
        CustomerBean bean=new CustomerBean();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
        if (!isMultipart) {
            return;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator i = fileItems.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(result + fileName.substring(fileName.lastIndexOf("\\")));
                        out.println("i am in condition one");
                    } else {
                        file = new File(result + fileName.substring(fileName.lastIndexOf("\\")+1));
                        out.println("i am in condition two");
                    }
                    fi.write(file);
                    bean.setC_img("uploads/"+fileName);
                    out.println("Uploaded Filename: " + fileName + "<br>");
                }else{
                     if (fi.getFieldName().equals("firstName")) {
                            bean.setFirstName(fi.getString());
                        }else if(fi.getFieldName().equals("lastName")){
                             bean.setLastName(fi.getString());
                        }else if(fi.getFieldName().equals("year")){
                             year=parseInt(fi.getString());
                             
                        }else if(fi.getFieldName().equals("month")){
                             month=parseInt(fi.getString());
                        }else if(fi.getFieldName().equals("Day")){
                             day=parseInt(fi.getString());
                             bean.setUserBDate(year+"-"+month+"-"+day);
                        }else if(fi.getFieldName().equals("userPassword")){
                             bean.setUserPassword(fi.getString());
                        }else if(fi.getFieldName().equals("userMobile")){
                             bean.setUserMobile(fi.getString());
                        }else if(fi.getFieldName().equals("userCredit")){
                            String cr=fi.getString();
                            credit=parseFloat(cr);
                            bean.setUserCredit(credit);
                        }else if(fi.getFieldName().equals("userAddress")){
                             bean.setUserAddress(fi.getString());
                        }else if(fi.getFieldName().equals("userMail")){
                             bean.setUserMail(fi.getString());
                        }
                }
            }
            
           CustomerDataBase customer=new CustomerDataBase();
           int returnval= customer.fillCustomer(bean);
          if(returnval>=1){
              HttpSession session=request.getSession(true);
              session.setAttribute("user", bean);
              RequestDispatcher rd=request.getRequestDispatcher("main.jsp");
              rd.forward(request, response);
          }else{
              RequestDispatcher rd=request.getRequestDispatcher("signupmain.jsp");
              rd.forward(request, response);
          }
            
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        throw new ServletException("GET method used with ");
         
}
}
